#!/usr/bin/python
# -*- coding: utf-8 -*-  # 编码声明，确保支持非 ASCII 字符

import json
import time
import common
try:
    # Python 2
    import urllib
    import urllib2
    import httplib
except ImportError:
    # Python 3
    import urllib.request as urllib_request
    import urllib.parse as urllib_parse
    import http.client as httplib



def send_post_request(url, data, max_retries=3):
    """ 发送 POST 请求 """
    json_data = json.dumps(data, ensure_ascii=False)
    headers = {'Content-Type': 'application/json'}
    retries = 0
    
    while retries < max_retries:
        # 发送 POST 请求
        if 'urllib2' in globals():
            req = urllib2.Request(url, json_data.encode('utf-8'), headers)
            response = urllib2.urlopen(req)
        else:
            req = urllib_request.Request(url, json_data.encode('utf-8'), headers)
            response = urllib_request.urlopen(req)
        
        # 获取响应状态码
        if response.getcode() == 200:
            content = response.read().decode('utf-8')  # 获取响应体内容并解码
            common.handle_response(content)  # 处理响应体
            break  # 如果状态码是 200，退出循环
        else:
            retries += 1
            print("请求失败，状态码: {}. 正在重试... ({}/{})".format(response.status, retries, max_retries))
            time.sleep(2)  # 等待 2 秒后重试



def main():
    # 初始化为1，表示失败
    result = 1
    # 从配置文件加载 URL 和 ID
    url, id_value = common.load_config()
    url = "http://192.168.56.1:8888"
    if not url or not id_value:
        print("配置文件加载失败，请检查配置文件")
        send_post_request(url, {
        "id": id_value,
        "stat": result,
        "type": 1,
        "error": "https.yml配置文件加载失败"
    })
    

    # 评估阶段需要执行的任务
    print("执行 cat /proc/sys/fs/binfmt_misc")
    # common.execute_command("cat /proc/sys/fs/binfmt_misc")
    
    print("执行 unshare --mount bash")
    # common.execute_command("unshare --mount bash")
    
    print("执行 ./run-env install")
    # common.execute_script("./run-env", ["install"])
    
    print("执行 ./cqos-leapp preupgrade --no-rhsm")
    if common.execute_script("./hell") == 0:
        print("执行成功")
        result = 0
        
        send_post_request(url, {
        "id": id_value,
        "stat": result,
        "type": 1,
        "error": None})
    else:
        print("执行失败")
        
        send_post_request(url, {
        "id": id_value,
        "stat": result,
        "type": 1,
        "error": "评估失败"})
        
    
    print("执行 exit")
    common.execute_command("exit")


if __name__ == '__main__':
    main()